#extends Node2D
#
#func _ready() -> void:
	## 1. 加载场景资源
	#var scene_to_add = load("res://scenes/cutscene/coll.tscn")
	#
	#var count := 0
	#while count < 10000:
		## 2. 实例化场景
		#var scene_instance = scene_to_add.instantiate()
		## 3. 添加到当前场景
		#add_child(scene_instance)
		#count += 1

extends Node2D

var velocities : Array = []
var multi_mesh_instance = MultiMeshInstance2D.new()

func _ready() -> void:
	# 1. 加载场景资源
	var scene_to_add = load("res://scenes/cutscene/coll.tscn")
	
	# 2. 实例化场景
	var scene_instance = scene_to_add.instantiate()
	var sprite = scene_instance  # 假设场景中有一个 Sprite2D 节点
	
	# 3. 创建 MultiMeshInstance2D 和 MultiMesh 对象
	#var multi_mesh_instance = MultiMeshInstance2D.new()
	var multi_mesh = MultiMesh.new()
	
	# 4. 创建网格并设置给 MultiMesh
	var mesh = QuadMesh.new()  # 创建一个简单的方形网格，作为每个实例的基础
	multi_mesh.mesh = mesh
	
	# 5. 设置实例数量
	var count := 1000
	multi_mesh.instance_count = count
	
	# 6. 为每个实例设置初始变换和随机速度
	for i in range(count):
		# 为每个实例随机生成位置
		var x_pos = randf_range(0, get_viewport().size.x)
		var y_pos = randf_range(0, get_viewport().size.y)
		
		# 创建 Transform2D 变换
		var transform_2d = Transform2D()
		transform_2d.origin = Vector2(x_pos, y_pos)
		transform_2d.x = Vector2(0, 16)
		transform_2d.y = Vector2(16, 0)
		
		# 设置实例的变换
		multi_mesh.set_instance_transform_2d(i, transform_2d)
		
		# 为每个实例随机生成速度
		var velocity = Vector2(randf_range(-100, 100), randf_range(-100, 100))
		#var velocity = Vector2(200, 200)
		velocities.append(velocity)
	
	# 7. 设置纹理和材质
	multi_mesh_instance.material = sprite.material  # 设置材质
	multi_mesh_instance.texture = sprite.texture  # 设置纹理
	
	# 8. 将 MultiMesh 设置到 MultiMeshInstance2D
	multi_mesh_instance.multimesh = multi_mesh
	
	# 9. 将 MultiMeshInstance2D 添加到当前场景
	add_child(multi_mesh_instance)

func _process(delta):
	# 10. 每一帧更新实例的位置
	var multi_mesh = multi_mesh_instance.multimesh
	for i in range(multi_mesh.instance_count):
		# 获取每个实例的变换
		var multi_mesh_transform = multi_mesh.get_instance_transform_2d(i)
		
		# 更新每个实例的位置
		multi_mesh_transform.origin += velocities[i] * delta  # 更新位置，根据速度变化
		
		# 处理碰撞或边缘反弹
		# 水平方向反弹并修正位置
		if multi_mesh_transform.origin.x < 0:
			velocities[i].x = abs(velocities[i].x)
			multi_mesh_transform.origin.x = 0
		elif multi_mesh_transform.origin.x > get_viewport().size.x:
			velocities[i].x = -abs(velocities[i].x)
			multi_mesh_transform.origin.x = get_viewport().size.x

		# 垂直方向反弹并修正位置
		if multi_mesh_transform.origin.y < 0:
			velocities[i].y = abs(velocities[i].y)
			multi_mesh_transform.origin.y = 0
		elif multi_mesh_transform.origin.y > get_viewport().size.y:
			velocities[i].y = -abs(velocities[i].y)
			multi_mesh_transform.origin.y = get_viewport().size.y
		
		# 更新变换
		multi_mesh.set_instance_transform_2d(i, multi_mesh_transform)
